<template>
  <!--size抽屉宽度（或高度）  default 378px 和 large 736px -->
  <a-drawer
      v-model:open="visible"
      ref="employeeDetailModalRef"
      class="edit-drawer modal-fixed-bottom"
      root-class-name="root-customer-drawer"
      width="800px"
      :closable="false"
      @close="onClose"
  >
    <div class="closeable" @click="onClose">{{ $t('self.closeButton') }}</div>
    <div class="modal-header">{{ title }}</div>
    <a-form :model="formState" :rules="formRules" :label-col="labelCol" :wrapper-col="wrapperCol"
            @finish="onSubmit"
    >
      <a-form-item :label="$t('self.userBind.tips1')" name="userName">
<!--        @change="handleChange"-->
        <a-select
            v-model:value="formState.userName"
            show-search
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="searchFormUsernameOptions"
            :fieldNames="{ label: 'userName', value: 'id' }"
            @search="handleSearchUser"
            @change="handleChangeUser"
        >
          <template v-if="searchFormUsernameLoading" #notFoundContent>
            <a-spin size="small" />
          </template>
        </a-select>
      </a-form-item>
      <a-form-item :label="$t('self.userBind.tips5')" name="status">
        <a-select v-model:value="formState.status" :options="[
            { label: $t('self.userBind.status.tips0'), value: 0 },
            { label: $t('self.userBind.status.tips1'), value: 1 },
        ]" />
      </a-form-item>
<!--      <a-form-item :label="$t('self.userBind.tips7')" name="dataType">-->
<!--        <a-select v-model:value="formState.dataType" :options="[-->
<!--            { label: $t('self.userBind.dataType.tips1'), value: 1 },-->
<!--            { label: $t('self.userBind.dataType.tips2'), value: 2 },-->
<!--        ]" />-->
<!--      </a-form-item>-->
      <a-form-item :label="$t('self.userBind.tips8')" name="no">
        <a-input allow-clear v-model:value="formState.no" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.userBind.tips11')" name="password">
        <a-input allow-clear v-model:value="formState.password" placeholder="" />
      </a-form-item>
      <a-form-item :label="$t('self.userBind.tips9') + $t('self.userBind.tips12')" name="expiryDate">
        <a-date-picker v-model:value="formState.expiryDate" :format="dateFormat" style="width: 100%;"></a-date-picker>
      </a-form-item>
      <a-form-item :label="$t('self.userBind.tips16')" name="remark">
        <a-input allow-clear v-model:value="formState.remark" placeholder="" />
      </a-form-item>

      <div class="base-flex base-rows base-align-items-center base-justify-content-center footer">
        <a-button type="primary" html-type="submit">{{ $t('self.submitButton') }}</a-button>
        <a-button class="base-ml10" @click="onClose">{{ $t('self.cancelButton') }}</a-button>
      </div>

    </a-form>

  </a-drawer>
</template>

<script setup>
import { computed, getCurrentInstance, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { userStore } from '@/stores/userStore'
const { proxy } = getCurrentInstance()
const $TOOL = proxy.$TOOL
const $API = proxy.$API
const $T = proxy.$t
const emit = defineEmits(['close','ok'])
const useUserStore = userStore()

const visible = ref(false)
// 模式，add新增，show查看，edit编辑
const mode = ref('add')
const labelCol = {
  style: {
    width: '230px',
  },
};
const wrapperCol = {
  span: 16,
};
const title = ref('')
const formState = ref({
  id: '',
  orgId: null,
  userName: '',
  totalMoney: '',
  status: 1, // 账户状态  2过期 1正常，0冻结
  dataType: 1, // 卡类型，默认为1
  no: '',
  expiryDate: '',
  password: '',
  remark: '',
  userId: ''
})
const dateFormat = ref('YYYY-MM-DD')
const searchFormUsernameLoading = ref(false)
const searchFormUsernameOptions = ref([])

const handleSearchUser = (value) => {
  const params = {
    mobile: value
  }
  $API.backend.user.list.post(params).then(res => {
    const { objData } = res
    searchFormUsernameOptions.value = objData.data
  }).catch(err => {
    message.error(err.msg);
  })
}

const handleChangeUser = (value, option) => {
  // console.log(value, option)
  formState.value.userId = option.userId
}

const orgOptions = ref([])

const formRules = ref({
  orgId: [{required: true,message: $T('self.pleaseChoose') + $T('self.userBind.tips13'),trigger: 'change'}],
  // userName: [{required: true,message: $T('self.pleaseInput') + $T('self.userBind.tips1'),trigger: 'change'}],
  status: [{required: true,message: $T('self.pleaseChoose') + $T('self.userBind.tips5'),trigger: 'change'}],
  dataType: [{required: true,message: $T('self.pleaseChoose') + $T('self.userBind.tips7'),trigger: 'change'}],
  no: [{required: true,message: $T('self.pleaseInput') + $T('self.userBind.tips8'),trigger: 'change'}],
  password: [{required: true,message: $T('self.pleaseInput') + $T('self.userBind.tips11'),trigger: 'change'}],
  expiryDate: [{required: true,message: $T('self.pleaseInput') + $T('self.userBind.tips12'),trigger: 'change'}],
})

onMounted(async () => {
  // orgOptions.value = await proxy.getOrgSelectList(true)
})

const onSubmit = (values) => {
  const params = { ...formState.value }
  // 日期处理 / 日期转换
  params.expiryDate = dayjs(params.expiryDate).format('YYYY-MM-DD')
  if(mode.value === 'add') {
    // 添加
    $API.backend.userBind.add.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg || $T('self.message.error'))
    })
  }else{
    // 修改
    $API.backend.userBind.edit.post(params).then(res => {
      message.success($T('self.message.success'))
      onReset()
      visible.value = false
      emit('ok')
    }).catch(err => {
      message.error(err.msg || $T('self.message.error'))
    })
  }
  // console.log(formState.value)
  // console.log('submit!', values);
}

const onReset = () => {
  // 清空内容
  formState.value = {
    id: '',
    orgId: null,
    userName: '',
    totalMoney: '',
    status: 1, // 账户状态  2过期 1正常，0冻结
    dataType: 1, // 卡类型，默认为1
    no: '',
    expiryDate: '',
    password: '',
    remark: '',
    userId: ''
  }
}

const onClose = () => {
  onReset()
  visible.value = false
  emit('close')
}

const add = () => {
  mode.value = 'add'
  title.value = $T('self.userBind.tips14')
  visible.value = true
}

const edit = (record) => {
  mode.value = 'edit'
  // 其他信息不要
  $TOOL.array.cloneExistKey(formState.value, record)
  // formState.value = { ...record }
  // 日期处理 / 日期转换
  formState.value.expiryDate = formState.value.expiryDate ? dayjs(formState.value.expiryDate, dateFormat.value) : ''
  title.value = $T('self.userBind.tips15')
  visible.value = true
  // detail.value = record
  // console.log(formState.value)
}

// 子组件中要通过defineExpose将方法暴露给父组件
defineExpose({
  add,
  edit,
})
</script>

<style lang="scss" scoped>
.edit-drawer {
  position: relative;
  .closeable {
    @include closeable;
  }
}
</style>
